from rest_framework import serializers
from app01 import models


class PublisherSerializer(serializers.Serializer):
	id = serializers.IntegerField()
	name = serializers.CharField()


class PublisherModelSerializer(serializers.ModelSerializer):
	class Meta:
		model = models.Publisher
		fields = "__all__"


class AuthorSerializer(serializers.Serializer):
	id = serializers.IntegerField()
	name = serializers.CharField()


class AuthorModelSerializer(serializers.ModelSerializer):
	class Meta:
		model = models.Author
		fields = "__all__"


def check_title(value):
	if 'xxx' in value:
		raise serializers.ValidationError('不能包含xxx')
	else:
		return value


class BookSerializer(serializers.Serializer):
	id = serializers.IntegerField(required=False)
	title = serializers.CharField(validators=[check_title])
	pub_date = serializers.DateField()
	category = serializers.CharField(source='get_category_display', read_only=True)
	# book_obj.category    book_obj.get_category_display()
	publisher = PublisherSerializer(read_only=True)
	authors = AuthorSerializer(many=True, read_only=True)

	post_category = serializers.CharField(write_only=True)
	post_publisher = serializers.IntegerField(write_only=True)
	post_authors = serializers.ListField(write_only=True, )

	def validate_title(self, attrs):
		"""局部钩子"""
		if '人妖' in attrs:
			raise serializers.ValidationError('不合法')
		else:
			return attrs

	def validate(self, attrs):
		"""全局钩子"""

	#  通过校验返回所有数据
	#  不通过校验盘抛出异常

	def create(self, validated_data):
		print(validated_data)
		book_obj = models.Book.objects.create(
			title=validated_data['title'],
			category=validated_data['post_category'],
			pub_date=validated_data['pub_date'],
			publisher_id=validated_data['post_publisher'],
		)
		book_obj.authors.set(validated_data['post_authors'])
		return book_obj

	def update(self, instance, validated_data):
		instance.title = validated_data.get('title', instance.title)
		instance.category = validated_data.get('post_category', instance.category)
		instance.pub_date = validated_data.get('pub_date', instance.pub_date)
		instance.publisher_id = validated_data.get('post_publisher', instance.publisher_id)
		instance.save()

		instance.authors.set(validated_data.get('post_authors', instance.authors.all()))

		return instance


class BookModelSerializer(serializers.ModelSerializer):
	category_info = serializers.SerializerMethodField()  # 找  get_字段名的方法 执行
	publisher_info = serializers.SerializerMethodField()
	author_info = serializers.SerializerMethodField()

	def get_category_info(self, obj):
		return obj.get_category_display()

	def get_publisher_info(self, obj):
		# ret = {
		# 	'id' : obj.publisher_id,
		# 	'name':obj.publisher.name,
		# }
		# return ret
		ser_obj = PublisherSerializer(obj.publisher)
		return ser_obj.data

	def get_author_info(self, obj):
		ser_obj = AuthorSerializer(obj.authors.all(), many=True)
		return ser_obj.data

	class Meta:
		model = models.Book
		fields = '__all__'
		# depth = 1  # 跟对象关联的内容  属性read_only = True
		# exclude = []
		extra_kwargs = {
			'category': {'write_only': True, },
			'publisher': {'write_only': True},
			'authors': {'write_only': True},
		}
